package study.web.user;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import study.domain.user.User;
import study.domain.user.UserSearch;
import study.service.user.UserService;

import com.barney.support.web.WebList;

/**
 * 사용자 컨트롤러
 *
 * @author Barney Kim
 */
@Slf4j
@Controller
@RequestMapping("/users")
public class UserController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, ModelMap model) {
		return "users/login";
	}

	@Secured({ "ROLE_ADMIN_USER" })
	@RequestMapping("")
	public String list(UserSearch search, ModelMap model) {
		log.debug("{}", search);
		WebList<User> users = userService.getUsers(search);
		model.addAttribute("result", users);
		model.addAttribute("search", search);
		return "users/list";
	}

	@PreAuthorize("hasRole('ROLE_ADMIN_USER')")
	@RequestMapping("/{username}")
	public String show(@PathVariable("username") String username,
			UserSearch search, ModelMap model) {
		log.debug("{}", search);
		User user = userService.getUserByUsername(username);
		model.addAttribute("user", user);
		model.addAttribute("search", search);
		return "users/show";
	}
}
